package mo.leetcode_top;

import java.util.HashSet;
import java.util.Set;

public class L36 {

    public boolean isValidSudoku(char[][] board) {
        //check row and column
        for (int i = 0; i < 9; i++) {
            boolean[] row = new boolean[9];
            boolean[] column = new boolean[9];
            for (int j = 0; j < 9; j++) {
                if (Character.isDigit(board[i][j])) {
                    if (row[board[i][j]-'0'-1]) {
                        return false;
                    } else {
                        row[board[i][j]-'0'-1] = true;
                    }
                }

                if (Character.isDigit(board[j][i])) {
                    if (column[board[j][i]-'0'-1]) {
                        return false;
                    } else {
                        column[board[j][i]-'0'-1] = true;
                    }
                }
            }
        }

        //check 3X3
        for (int i = 1; i < 9; i+=3) {
            for (int j = 1; j < 9; j+=3) {

                Set<Character> firstDigital = new HashSet<>();
                for (int x = i-1; x <= i+1; x++) {
                    for (int y = j-1; y <= j+1; y++) {
                        if (Character.isDigit(board[x][y])) {
                            if (firstDigital.contains(board[x][y])) {
                                return false;
                            } else {
                                firstDigital.add(board[x][y]);
                            }
                        }
                    }
                }

            }
        }

        return true;
    }

}
